package com.ddwl.message.service;

import com.alibaba.fastjson.JSON;
import com.ddwl.message.constant.MessageConstant;
import com.ddwl.message.getui.template.PushTemplate;
import com.ddwl.message.getui.util.IGtPushUtil;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.*;
import com.gexin.rp.sdk.http.IGtPush;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import com.gexin.rp.sdk.template.StartActivityTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 消息推送Service接口实现
 *
 * @author Aaric, created on 2018-07-27T11:02.
 * @since 0.1.0
 */
@Service
@Slf4j
public class MessagePushService{

    /**
     * 个推-AppID
     */
    @Value("${getui.appId}")
    private String appId;

    /**
     * 个推-AppKey
     */
    @Value("${getui.appKey}")
    private String appKey;

    /**
     * 个推-AppSecret
     */
    @Value("${getui.masterSecret}")
    private String masterSecret;

    /**
     * 个推-SDK地址
     */
    @Value("${getui.sdkUrl}")
    private String sdkUrl;

    @Async
    public String pushToList(String msgTitle, String msgText, String transContent, List<String> clientIdList) {
        // 检查数据合法性
        if (!StringUtils.hasText(msgTitle) || !StringUtils.hasText(msgText) || !StringUtils.hasText(transContent) || null == clientIdList || 0 == clientIdList.size()) {
            throw new IllegalArgumentException("the required params can't be empty");
        }
        // 推送给一个用户集合
        ListMessage message = getListMessage(msgTitle, msgText, transContent);
        // 指定对象集合
        Target target;
        List<Target> targetList = new ArrayList<>();
        for (String clientId : clientIdList) {
            target = new Target();
            target.setAppId(appId);
            target.setClientId(clientId);
            targetList.add(target);
        }
        // 返回taskId信息
        IGtPush gtPush = IGtPushUtil.getIGtPush(appKey, masterSecret);
        IPushResult result = gtPush.pushMessageToList(gtPush.getContentId(message), targetList);
        if (null != result) {
            Map<String, Object> response = result.getResponse();
            log.info("[pushToList response : {}]", JSON.toJSONString(response));
            if (null != response && "ok".equals(response.get("result"))) {
                return response.get("contentId").toString();
            }
        }
        return null;
    }

    @Async
    public String pushToAll(String msgTitle, String msgText, String transContent) {
        // 检查数据合法性
        if (!StringUtils.hasText(msgTitle) || !StringUtils.hasText(msgText) || !StringUtils.hasText(transContent)) {
            throw new IllegalArgumentException("the required params can't be empty");
        }
        // 推送给所有APP用户
        AppMessage message = getAppMessage(msgTitle, msgText, transContent);
        // 推送给App的目标用户需要满足的条件
        List<String> appIdList = new ArrayList<>();
        appIdList.add(appId);
        message.setAppIdList(appIdList);

        // 返回taskId信息
        IGtPush gtPush = IGtPushUtil.getIGtPush(appKey, masterSecret);
        IPushResult result = gtPush.pushMessageToApp(message);
        if (null != result) {
            Map<String, Object> response = result.getResponse();
            log.info("[pushToList response : {}]", JSON.toJSONString(response));
            if (null != response && "ok".equals(response.get("result"))) {
                return response.get("contentId").toString();
            }
        }
        return null;
    }

    private String sendAllMsg(AppMessage message, IGtPush gtPush, IPushResult result, int count, String msgTitle) {
        String msg = null;
        boolean flag = false;
        if (count >= 3) {
            return msg;
        }
        count++;
        try {
            result = gtPush.pushMessageToApp(message);
            if (null != result) {
                Map<String, Object> response = result.getResponse();
                log.info("[pushToList response : {}]", JSON.toJSONString(response));
                if (null != response && "ok".equals(response.get("result"))) {
                    return response.get("contentId").toString();
                } else {
                    log.error("{} - push All failure, cause: {}", msgTitle, response.get("result").toString());
                }
            } else {
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = true;
        }
        if (flag) {
            log.error("{} - push All failure: count:{}", msgTitle, count);
            msg = sendAllMsg(message, gtPush, result, count, msgTitle);
        }
        return msg;
    }

    private SingleMessage getSingleMessage(String msgTitle, String msgText, String transContent) {
        SingleMessage message = new SingleMessage();
        return (SingleMessage) getTransmissionTemplateMessage(message, msgTitle, msgText, transContent);
    }

    private ListMessage getListMessage(String msgTitle, String msgText, String transContent) {
        ListMessage listMessage=new ListMessage();
        return (ListMessage) getTransmissionTemplateMessage(listMessage, msgTitle, msgText, transContent);
    }

    private AppMessage getAppMessage(String msgTitle, String msgText, String transContent) {
        AppMessage appMessage=new AppMessage();
        return (AppMessage) getTransmissionTemplateMessage(appMessage, msgTitle, msgText, transContent);
    }

    private Message getTransmissionTemplateMessage(Message message,String msgTitle, String msgText, String transContent) {
        TransmissionTemplate template = PushTemplate.getTransmissionTemplate(msgTitle, msgText, transContent);
        template.setAppId(appId);
        template.setAppkey(appKey);
        message.setData(template);
        // 设置消息离线，并设置离线时间
        message.setOffline(true);
        //离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(MessageConstant.DEFAULT_OFFLINE_EXPIRE_TIME);
        //网络环境：1为wifi，0为不限制网络环境
        message.setPushNetWorkType(MessageConstant.DEFAULT_PUSH_NETWORK_TYPE);
        // 厂商下发策略；1: 个推通道优先，在线经个推通道下发，离线经厂商下发(默认);2: 在离线只经厂商下发;3: 在离线只经个推通道下发;4: 优先经厂商下发，失败后经个推通道下发;
        message.setStrategyJson("{\"default\":1,\"ios\":1,\"st\":1}");
        return message;
    }

    private Message getStartActivityTemplateMessage(Message message,String msgTitle, String msgText, String transContent) {
        StartActivityTemplate template = PushTemplate.getStartActivityTemplate(msgTitle, msgText, transContent);
        template.setAppId(appId);
        template.setAppkey(appKey);
        message.setData(template);
        // 设置消息离线，并设置离线时间
        message.setOffline(true);
        //离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(MessageConstant.DEFAULT_OFFLINE_EXPIRE_TIME);
        //网络环境：1为wifi，0为不限制网络环境
        message.setPushNetWorkType(MessageConstant.DEFAULT_PUSH_NETWORK_TYPE);
        // 厂商下发策略；1: 个推通道优先，在线经个推通道下发，离线经厂商下发(默认);2: 在离线只经厂商下发;3: 在离线只经个推通道下发;4: 优先经厂商下发，失败后经个推通道下发;
        message.setStrategyJson("{\"default\":1,\"ios\":4,\"st\":1}");
        return message;
    }

}
